package com.jredu.controller;

import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.jredu.util.CheckUtil;
import com.jredu.util.EventDispatcher;
import com.jredu.util.MessageUtil;
import com.jredu.util.MsgDispatcher;

@Controller
@RequestMapping("/app")
public class WechatSecurity {
	private static Logger logger = Logger.getLogger(WechatSecurity.class);
	
	@RequestMapping(value = "/security", method = RequestMethod.GET)
	public void doGet(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "signature", required = false) String signature,
            @RequestParam(value = "timestamp", required = false) String timestamp,
            @RequestParam(value = "nonce", required = false) String nonce,
            @RequestParam(value = "echostr", required = false) String echostr) {
        try {
            if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
                PrintWriter out = response.getWriter();
                System.out.print("sdsadasd");
                out.print(echostr);
                out.close();
            } else {
                logger.info("这里存在非法请求！");
            }
        } catch (Exception e) {
            logger.error(e, e);
        }
    }
	
	@RequestMapping(value = "/security", method = RequestMethod.POST)
    // post 方法用于接收微信服务端消息
    public void DoPost(HttpServletRequest request,HttpServletResponse response) {
        System.out.println("进入方法！");
        try{
        	response.setCharacterEncoding("utf-8");
            Map<String, String> map=MessageUtil.parseXml(request);
            String msgtype=map.get("MsgType");
            if(MessageUtil.REQ_MESSAGE_TYPE_EVENT.equals(msgtype)){
                EventDispatcher.processEvent(map); //进入事件处理
            }else{
            	String respXML = MsgDispatcher.processMessage(map); //进入消息处理
            	PrintWriter out = response.getWriter();
            	out.print(respXML);
            	out.flush();
            	out.close();  
            }
        }catch(Exception e){
            logger.error(e,e);
        }
    }
	

}
